package isquirrel.servlets;

import isquirrel.UserManager;
import isquirrel.beans.Url;
import isquirrel.beans.User;
import isquirrel.error.CannotLoginUserException;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.Set;

import javax.servlet.ServletException;

import org.json.JSONException;

/**
 * Servlet implementation class Shuffle
 */
public class Shuffle extends HttpDBServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Shuffle() {
    }


	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
		String userToken = request.getParameter("t"); 			//token
		String auth_method = request.getParameter("au");        //authentication method 
		String user = request.getParameter("user");  			//username
				
		boolean loggedin = false;
		boolean istoken = false;
		
		if (auth_method != null){
			if (auth_method.equals("to")){
				loggedin = UserManager.tokenLogin(user,userToken);
				istoken=true;
			}		
			if (loggedin) {
				User u = null;
				if (istoken){
					u  = UserManager.getUser(user);
				}
				Set<Url> urls = u.getUrls();
				if (urls == null || urls.size() == 0) {
					response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/error.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:0.85em'>Shuffling is disabled. You haven't added any interests in your profile yet.</div>");
				}
				else {
					Object[] urlsArray = urls.toArray();
					Random generator = new Random(new Date().getTime());
					Url randomUrl = (Url)	urlsArray[generator.nextInt(urlsArray.length)];
					response.getWriter().print(randomUrl.getAddress());
				}
			}
			else {
				response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/error.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:1.15em'>An error occured. Please try again.</div>");
				throw new CannotLoginUserException();
			}
		}
		else {
			response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/error.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:1.15em'>An error occured. Please try again.</div>");
			throw new CannotLoginUserException();
		}
	}

	@Override
	protected void handlePost() throws ServletException, IOException, CannotLoginUserException, 
			JSONException {
	}

}
